package com.lyf.boot.modules.index.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.RandomUtil;
import com.lyf.boot.constant.RedisConstant;
import com.lyf.boot.enums.SmsType;
import com.lyf.boot.modules.index.entity.dto.SmsDto;
import com.lyf.boot.modules.index.service.ISmsService;
import com.lyf.boot.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 短信服务
 * @author Luyufan
 * @date 2023/7/5 19:06
 */
@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements ISmsService {

    @Override
    public void sendSms(SmsDto dto) {
        String smsCode = RandomUtil.randomString("123456789", 4);
        String phoneNumber = dto.getPhoneNumber();
        SmsBlend smsBlend = SmsFactory.getSmsBlend();
        Map<String,String> params = MapUtil.newHashMap(2, true);
        params.put("code", smsCode);
        smsBlend.sendMessage(phoneNumber, "SMS_253120590", (LinkedHashMap<String, String>) params);
        String smsCodeKey = StrFormatter.format(RedisConstant.SMS_CODE_KEY, SmsType.LOGIN.name(), phoneNumber);
        RedisUtil.setCacheObject(smsCodeKey, smsCode, Duration.ofSeconds(RedisConstant.SMS_EXPIRE));
    }
}
